package weixin_new.Servlet;
import java.io.IOException;  
import java.io.PrintWriter;  
import java.io.UnsupportedEncodingException;

import javax.annotation.Resource;
import javax.servlet.ServletException;  
import javax.servlet.http.HttpServlet;  
import javax.servlet.http.HttpServletRequest;  
import javax.servlet.http.HttpServletResponse;  

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import weixin_new.bean.MyCheck;
import weixin_new.service.CoreService;
public class Weixin_newServlet extends HttpServlet{  
	
	/**  
	 * 这个方法用于接收用于通过微信公账号发送过来的信息处理
	 * 微信公众号的内容聊天的内容
	 */  

	private CoreService coreService;  

	@RequestMapping(method = RequestMethod.GET)  

	public void doGet(HttpServletRequest request, HttpServletResponse response)  
			throws ServletException, IOException {  
		// 微信加密签名  
		String signature = request.getParameter("signature");  
		// 时间戳  
		String timestamp = request.getParameter("timestamp");  
		// 随机数  
		String nonce = request.getParameter("nonce");  
		// 随机字符串  
		String echostr = request.getParameter("echostr");  

		PrintWriter out = response.getWriter();  
		
		//这里是我自己的测试使用的，不是微信时需要使用的方法  
		if(signature.equals("1")) {  
			//这里是返回的信息  
			out.print("1111111");  
		}  
		// 通过检验signature对请求进行校验，若校验成功则原样返回echostr，表示接入成功，否则接入失败  
		if (MyCheck.checkSignature(signature, timestamp, nonce)) {  
			out.print(echostr);  
		}  

		out.close();  
		out = null;  
	}  
	public void doPost(HttpServletRequest request, HttpServletResponse response) {  
		try {  
			request.setCharacterEncoding("UTF-8");  
		} catch (UnsupportedEncodingException e) {  
			e.printStackTrace();  
		}  

		System.out.println("==========微信公众号收到用户发送的消息了==========");
		
		response.setCharacterEncoding("UTF-8"); 
		
		// 调用核心业务类接收消息、处理消息  
		String respMessage = coreService.processRequest(request);  

		// 响应消息  
		PrintWriter out = null;  
		try {  
			out = response.getWriter();  
			out.print(respMessage);  
		} catch (IOException e) {  
			e.printStackTrace();  
		} finally {  
			out.close();  
			out = null;  
		}  
	}  

}  